package com.hzw.saas.common.config.util;

import cn.hutool.http.HttpUtil;
import com.hzw.saas.common.util.Json;
import lombok.extern.slf4j.Slf4j;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.Objects;

@Slf4j
public class HolidayTimorUtils {

    private static final String URL = "http://timor.tech/api/holiday/info/%s";
    private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");

    public static Boolean isHoliday(LocalDate date) {
        return isHoliday(date.format(DATE_TIME_FORMATTER));
    }

    public static Boolean isHoliday(LocalDateTime dateTime) {
        return isHoliday(dateTime.toLocalDate().format(DATE_TIME_FORMATTER));
    }

    public static Boolean isHoliday(Date date) {
        return isHoliday(date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate().format(DATE_TIME_FORMATTER));
    }

    private static Boolean isHoliday(String date) {
        try {
            String key = "timor" + date;
            if (RedisUtil.hasKey(key)) {
                return RedisUtil.get(key);
            }
            String result = HttpUtil.get(String.format(URL, date));
            Timor timor = Json.parseObject(result, Timor.class);
            boolean isHoliday = Objects.nonNull(timor) && Objects.nonNull(timor.holiday) && timor.holiday.holiday;
            RedisUtil.set(key, isHoliday, 24 * 60 * 60);
            return isHoliday;
        } catch (Exception e) {
            log.error("判断节假日出错", e);
            return Boolean.FALSE;
        }
    }

    private static class Timor {
        private Integer code;
        // null 非节假日
        private Holiday holiday;
    }

    private static class Holiday {
        // true 节假日
        private Boolean holiday;
    }
}